package com.jeesite.modules.sys.utils;

import com.baidu.aip.ocr.AipOcr;
import com.jeesite.common.config.Global;
import com.jeesite.common.io.FileUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.modules.sys.wx.qy.util.DeleteFile;
import com.jeesite.modules.sys.wx.qy.util.DloadImgUtil;
import com.jeesite.modules.sys.wx.qy.util.QyConfigUtil;
import org.json.JSONObject;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;

public class PicToWord {
    //设置APPID/AK/SK
    public static final String APP_ID = "14863171";
    public static final String API_KEY = "mXvG7cVPjUq4VAx0UjMlbUwn";
    public static final String SECRET_KEY = "WN4F7rfa57fsXbzHnr8nw5HGCOh7lL8f";


    public static String getBLiscenseMsg(HttpServletRequest request) throws InterruptedException {
        //获取图片
        String pic = request.getParameter("pic");

        //创建保存在文件管理器中的文件路径
        String filePath =  Global.getUserfilesBaseDir("");
        //创建保存数据库的图片路径
        String savePath = request.getContextPath() + File.separator +"userfiles";
        FileUtils.createDirectory(filePath);

        if (!StringUtils.isBlank(pic)) {
            pic = DloadImgUtil.downloadMedia(QyConfigUtil.getAccessToken(),"", pic, savePath, filePath);
            pic = pic.substring(pic.lastIndexOf("/")+1);
        }
        //获取图片路径
        pic = filePath + pic;
        System.out.println("路径地址:" + pic);
        //调用解析接口
        String picMsg = PicToWord.getBussinessLicenseMsg(pic);
        try {
            DeleteFile t = new DeleteFile();
            t.delete(pic);                  //删除照片
        } catch (Exception e) {
            // TODO: handle exception
        }
        return picMsg;
    }

    public static String getBussinessLicenseMsg(String image) {
        // 初始化一个AipOcr
        AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();

        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        // 参数为本地路径
        JSONObject res = client.businessLicense(image, options);

        return res.toString(2);

    }
}